package org.example.erpapispringweb.controller;



import org.example.erpapicommon.Util.ApiResult;
import org.example.erpapicommon.Util.ResponseType;
import org.example.erpapispringweb.security.ApiUser;
import org.example.erpapispringweb.security.Token;
import org.example.erpapispringweb.security.TokenException;
import org.example.erpapispringweb.TokenService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

//表示返回的不是视图而是对象。
@RestController
@RestControllerAdvice
public class MainController {
    final TokenService tokenService;
    public MainController(TokenService tokenService){
        this.tokenService = tokenService;
    }
    @PostMapping("/login")
    public ResponseEntity<Token> login(@RequestBody  ApiUser apiUser)throws TokenException {
        Token token = tokenService.createToken(apiUser);

        return ResponseEntity.ok(token);
    }

    @ExceptionHandler(TokenException.class)
    public ResponseEntity<ApiResult<?>> handleTokenException(TokenException e) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(ApiResult.fail(ResponseType.UNAUTHORIZED,e.getMessage()));
    }

}
